<template>
    <view class="release ph-32 pb-200">
        <Navigation backType="back" title="发布动态" :listenBack="true" @handleBack="handleBack" />
        <u-tabs
            :list="list"
            @click="changeType"
            lineColor="#FABB3C"
            lineWidth="32rpx"
            lineHeight="6rpx"
            :activeStyle="{ color: '#222222', fontWeight: '500' }"
            :inactiveStyle="{ color: '#222222', fontWeight: '500' }"
        ></u-tabs>
        <view class="mt-40" v-if="type == 0">
            <u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" multiple :maxCount="9" width="81" height="81">
                <view class="w-162 h-162 f ai-c jc-c b-8 upload">
                    <image src="http://cwht.ricecs.cn/app/novice/add.png" class="w-66 h-66"></image>
                </view>
            </u-upload>
        </view>
        <view class="mt-40" v-if="type == 1">
            <u-upload :fileList="videoList" @afterRead="afterRead" @delete="deletePic" multiple :maxCount="1" width="81" height="81" accept="video">
                <view class="w-162 h-162 f ai-c jc-c b-8 upload">
                    <image src="http://cwht.ricecs.cn/app/novice/add.png" class="w-66 h-66"></image>
                </view>
            </u-upload>
        </view>
        <view class="mt-24 h-100 f ai-c input fw-600">
            <u--input placeholder="请填写标题" border="none" v-model="params.title" :placeholderStyle="{ color: '#CCCCCC' }" fontSize="16"></u--input>
        </view>
        <view class="mt-29 fs-28 textarea">
            <u--textarea v-model="params.content" placeholder="此刻的想法~" autoHeight border="none" height="200" maxlength="-1"></u--textarea>
        </view>
        <view class="f fc-w">
            <scroll-view class="scroll-view_H" scroll-x="true">
                <view
                    class="box h-64 b-64 f ai-c jc-c mr-12 fs-26 text-color3 ph-24 mt-24"
                    v-for="(item, index) in oneCategory"
                    :key="index"
                    @click="changeOneCategory(index)"
                    :class="oneCurt == index ? 'active' : ''"
                    ># {{ item.categoryName }}</view
                >
            </scroll-view>
        </view>
        <!-- <view class="w-74 h-64 b-64 f ai-c jc-c box"><u-icon name="arrow-up" color="#999999" size="14"></u-icon></view> -->
        <!-- <view class="f fc-w">
            <view class="box h-64 b-64 f ai-c jc-c mr-12 fs-26 text-color3 ph-24 mt-24 active"># 狗粮1111</view>
            <view class="box h-64 b-64 f ai-c jc-c mr-12 fs-26 text-color3 ph-24 mt-24"># 狗粮</view>
            <view class="box h-64 b-64 f ai-c jc-c mr-12 fs-26 text-color3 ph-24 mt-24"># 狗粮</view>
            <view class="box h-64 b-64 f ai-c jc-c mr-12 fs-26 text-color3 ph-24 mt-24"># 狗粮</view>
        </view> -->
        <view class="mt-33 f ai-c jc-s-b h-96 address" @click="toAddress">
            
            <view class="f ai-c f1">
                <view class="f f1 fs-28 text-color4 mr-20 jc-f-e"
                    ><view class="w-f text-ellipsis-1">{{ params.address }}</view></view
                >
                <u-icon name="map" color="#999999" size="14"></u-icon>
            </view>
        </view>
        <view :style="{ paddingBottom: safeAreaBottom + 'px' }" class="bot w-f">
            <view class="f ai-c jc-s-b h-100 ph-40" >
                <view class="f ai-c fd-c" @click="submit(0)">
                    <image src="http://cwht.ricecs.cn/app/novice/draft.png" class="w-32 h-32"></image>
                    <view class="fs-20 text-color4 mt-8"> 存草稿</view>
                </view>
                <view class="f" @click="submit(1)">
                    <view class="w-572 h-72 fs-28 fw-600 text-color5 b-68 f ai-c jc-c btn" >发布</view>
                </view>
            </view>
        </view>
    </view>
</template>
<script setup lang="ts">
import { onShow } from '@dcloudio/uni-app';
import { contentCreate } from '@/services/api/novice';
import { categoryList, listParentcodes } from '@/services/api/index/index';
import { ref } from 'vue';
import { getUploadUrl } from '@/utils/env';
import { useAuthStore } from '@/store/modules/auth';
const authStore = useAuthStore();
const list = [
    {
        name: '照片',
    },
    {
        name: '视频',
    },
];
const type = ref(0);
const fileList = ref<any[]>([]);
const videoList = ref<any[]>([]);
const params = ref<any>({
    title: '',
    content: '',
    address: '',
    secondCategoryCode: '',
    urls: '',
    videoUrl: '',
    publishStatus: 1,
    memberId: authStore.getUserId,
    memberNickname: authStore.getUserInfo.nickname,
    avatar: authStore.getUserInfo.avatar,
});
const oneCategory = ref<any[]>([]);
const oneCurt = ref<number | null>(null);
onShow(() => {
	getCity()
    getCategoryList();
});
//发布
async function submit(publishStatus:number) {
    if (!params.value.title) {
        uni.showToast({
            title: '请输入标题',
            icon: 'none',
        });
        return;
    }
    if (!params.value.content) {
        uni.showToast({
            title: '请输入内容',
            icon: 'none',
        });
        return;
    }
    params.value.urls = '';
    params.value.videoUrl = '';
    params.value.publishStatus = publishStatus;
    if (type.value == 0 && fileList.value.length > 0) {
        params.value.urls = fileList.value
            .map((item) => {
                return item.url;
            })
            .join(',');
    }
    if (type.value == 1 && videoList.value.length > 0) {
        params.value.videoUrl = videoList.value
            .map((item) => {
                return item.url;
            })
            .join(',');
    }

    await contentCreate(params.value);
	if(publishStatus == 1){
		uni.showToast({
		    title: '发布成功',
		});
	}else{
		uni.showToast({
		    title: '保存成功',
		});
	}
  
    setTimeout(() => {
        var pages = getCurrentPages();
        var prevPage: any = pages[pages.length - 2];
        prevPage.setData({
            upDate: true,
        });
        uni.navigateBack();
    }, 1000);
}
//存草稿

//选择地址
function toAddress() {
    uni.chooseLocation({
        success: function (res) {
            params.value.address = res.address;
        },
    });
}
function getCity() {
		uni.getLocation({
			type: 'wgs84',
			geocode: true,
			success: function (res) {
				console.log(res);
				console.log('当前位置的纬度：' + res.latitude);
				let location = res.latitude + ',' + res.longitude;
				uni.request({
					url: 'https://apis.map.qq.com/ws/geocoder/v1/?location=location',
					data: {
						location: location,
						key: 'X3HBZ-6K2CX-JRP4Z-ZH4VQ-K2YNZ-IMFFD', //自己申请的Key
					},
					method: 'GET',
					success(res) {
						params.value.address = res.data.result.address_component.city
					},
				});
			},
			fail: function (res) {
				console.log(res);
			},
		});
	}
//获取一级分类
async function getCategoryList() {
    const { data } = await categoryList({ scope: 3, type: 2 });
    const parentCategoryCodes = data.map((item: any) => {
        return item.categoryCode;
    });
		oneCategory.value = data;
    //getListParentcodes(parentCategoryCodes);
}
//获取二级分类
async function getListParentcodes(parentCategoryCodes: any) {
    const { data } = await listParentcodes({ scope: 3, petType: 2, parentCategoryCodes: parentCategoryCodes });
    oneCategory.value = data;
}
function changeOneCategory(index: number) {
    oneCurt.value = index;
    params.value.secondCategoryCode = oneCategory.value[oneCurt.value].categoryCode;
}
function deletePic(event: any) {
    if (type.value == 0) {
        fileList.value.splice(event.index, 1);
    } else {
        videoList.value.splice(event.index, 1);
    }
}
function changeType(data: any) {
    type.value = data.index;
}
//返回
const handleBack = () => {
    uni.showModal({
        title: '提示',
        content: '当前内容未发布，是否保存？',
        confirmText: '保存草稿',
        confirmColor: '#FABB3C',
        cancelText: '删除草稿',
        cancelColor: '#222222',
        success: function (res) {
            if (res.confirm) {
				submit(0)
                uni.showToast({
                    title: '保存成功',
                });
                setTimeout(() => {
                    uni.navigateBack();
                }, 1000);
            } else if (res.cancel) {
                uni.navigateBack();
            }
        },
    });
};
// 新增图片
async function afterRead(event: any) {
    // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
    let lists = [].concat(event.file);
    if (type.value == 0) {
        let fileListLen = fileList.value.length;
        lists.map((item) => {
            fileList.value.push({
                ...item,
                status: 'uploading',
                message: '上传中',
            });
        });
        for (let i = 0; i < lists.length; i++) {
            const result = await uploadFilePromise(lists[i].url);
            let item = fileList.value[fileListLen];
            fileList.value.splice(
                fileListLen,
                1,
                Object.assign(item, {
                    status: 'success',
                    message: '',
                    url: result,
                })
            );
            fileListLen++;
        }
    } else {
        let fileListLen = videoList.value.length;
        lists.map((item) => {
            videoList.value.push({
                ...item,
                status: 'uploading',
                message: '上传中',
            });
        });
        for (let i = 0; i < lists.length; i++) {
            const result = await uploadFilePromise(lists[i].url);
            let item = videoList.value[fileListLen];
            videoList.value.splice(
                fileListLen,
                1,
                Object.assign(item, {
                    status: 'success',
                    message: '',
                    url: result,
                })
            );
            fileListLen++;
        }
    }
}
function uploadFilePromise(url: string) {
    return new Promise((resolve, reject) => {
        uni.uploadFile({
            url: getUploadUrl(),
            filePath: url,
            name: 'file',
            formData: {
                user: 'test',
            },
            success: (res) => {
                setTimeout(() => {
                    resolve(JSON.parse(res.data).data);
                }, 1000);
            },
        });
    });
}
//底部安全距离
const systemInfo = uni.getSystemInfoSync();
let safeArea = systemInfo.safeArea;
let screenHeight = systemInfo.screenHeight;
let safeAreaBottom = screenHeight - safeArea.bottom;
</script>
<style lang="scss" scoped>
.scroll-view_H {
    white-space: nowrap;
    width: 100%;
}
.release {
    .bot {
        position: fixed;
        left: 0;
        bottom: 0;
        background: #fff;
        border-top: 1px solid #f5f5f5;
        .btn {
            background: #fabb3c;
        }
    }
    .address {
        border-bottom: 1px solid #dddddd;
        border-top: 1px solid #dddddd;
    }
    .box {
        background: #f5f5f5;
        flex-shrink: 0;
        display: inline-block;
        line-height: 64rpx;
    }
    .active {
        color: #222222;
    }
    .textarea {
        min-height: 200rpx;
    }
    .input {
        border-bottom: 1px solid #dddddd;
    }
    ::v-deep .u-upload__wrap__preview {
        margin: 0 10rpx 10rpx 0 !important;
    }
    ::v-deep .u-upload__wrap__preview:nth-child(4n) {
        margin: 0 0 10rpx 0 !important;
    }

    .upload {
        border: 1rpx solid #dddddd;
    }
}
</style>
